package com.cloud.chat;



import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {

    // 定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    // 构造器
    // 初始化工作
    public GroupChatServer() {
        try {
            // 得到一个选择器
            selector = Selector.open();
            // serverSocketChannel
            listenChannel = ServerSocketChannel.open();
            // 绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置为非阻塞
            listenChannel.configureBlocking(false);
            // 将listenChannel注册到selector中
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);


        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // 监听
    public void listen() {
        while (true) {
            try {
                int count = selector.select(2000);
                if (count>0) {
                    // 如果count大于0，说明有事件需要处理
                    // 遍历得到的selector集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        // 取出selectionKey
                        SelectionKey selectionKey = iterator.next();
                        // 监听到accept
                        if (selectionKey.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            // 提示
                            System.out.println(socketChannel.getRemoteAddress() + "上线了~");
                        }
                        // 通过发送read事件，即通道是可读的状态
                        if (selectionKey.isReadable()) {
                            //处理读
                            read(selectionKey);
                        }
                        // 当前的key删除，防止重复处理
                        iterator.remove();
                    }
                } else {
//                    System.out.println("等待....");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // ...
            }

        }
    }

    // 读取客户端消息
    private void read(SelectionKey key){
        // 定义一个socketChannel
        SocketChannel channel = null;

        try {
            // 得到channel
            channel = (SocketChannel)key.channel();
            // 创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int count = channel.read(buffer);

            if (count > 0) {
                // 把缓冲区的数组转换成字符串
                String msg = new String(buffer.array());
                // 输出该消息
                System.out.println("msg = " + msg);

                // 向其他客户端转发消息，专门写一个方法来处理
                sendInfoToOtherClients(msg,channel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //向其他客户端转发消息（通道）,去掉自己
    public void sendInfoToOtherClients(String msg,SocketChannel self) {
        System.out.println("服务器转发消息中....");

        // 遍历所有注册到selector上的socketChannel，并排除自己
        for (SelectionKey key : selector.keys()) {
            // 通过key，取出对应的socketChannel
            Channel channel = key.channel();

            // 排除自己
            if (channel instanceof SocketChannel && channel != self) {
                // 转型
                SocketChannel socketChannel = (SocketChannel) channel;

                // 将msg 存储到buffer中
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());

                //将buffer的数据写入到通道了
                try {
                    socketChannel.write(byteBuffer);
                } catch (IOException e) {
                    try {
                        System.out.println(((SocketChannel) channel).getRemoteAddress() + "离线了...");
                        // 取消注册
                        key.cancel();
                        // 关闭通道
                        channel.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }
}
